package com.centling.smartSealForPhone.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.centling.smartSealForPhone.R;
import com.centling.smartSealForPhone.adapter.AuditorReviewAdapter;
import com.centling.smartSealForPhone.bean.AuditorSealRecordsBean;
import com.centling.smartSealForPhone.constants.UrlConstants;
import com.centling.smartSealForPhone.utils.LogUtil;
import com.centling.smartSealForPhone.utils.OkHttpUtil;
import com.centling.smartSealForPhone.utils.ShowToast;
import com.centling.smartSealForPhone.utils.TextLengthWatch;
import com.centling.smartSealForPhone.widget.AutoRecyclerView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.security.auth.login.LoginException;

import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;

/**
 * Created by Jessie on 2016/8/19.
 */
public class AuditorReviewActivity extends TitleBarActivity {

    private AutoRecyclerView reviewRv;
    private AuditorReviewAdapter auditorReviewAdapter;
    private GridLayoutManager manager;
    private PtrClassicFrameLayout ptrClassicFrameLayout;
    private LinearLayout loseLinearLayout;
    private RadioGroup reviewType, reviewLoseType;
    private int pageNo = 0;
    private String id = "";
    private String status = "6";
    private String reviewResultType = "RESHOOT";
    private List<AuditorSealRecordsBean> auditorSealRecordsBeanList = new ArrayList<>();
    private TextView reviewOk, reViewCancel, tips;
    private EditText reason;
    private RadioButton invalid, success, rePic;
    private TextView limitWords;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_auditor_review);
        id = getIntent().getStringExtra("sealApplyId");
        initView();
        reviewRv.setLayoutManager(manager);
        reviewRv.setAdapter(auditorReviewAdapter);
        ptrClassicFrameLayout.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout ptrFrameLayout) {
                sendListRequest(true);
            }
        });
        reviewOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sendRefuseRequest();
            }
        });
        reViewCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        reviewType.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.rb_auditor_review_success) {
                    loseLinearLayout.setVisibility(View.GONE);
                    auditorReviewAdapter.setReviewLose(false);
                    tips.setVisibility(View.GONE);
                    status = "6";
                } else {
                    rePic.setChecked(true);
                    loseLinearLayout.setVisibility(View.VISIBLE);
                    auditorReviewAdapter.setReviewLose(true);
                    tips.setVisibility(View.GONE);
                    status = "7";
                }
                reviewRv.getAdapter().notifyDataSetChanged();

            }
        });
        reviewLoseType.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                if (i == R.id.rb_auditor_review_invalid) {
                    auditorReviewAdapter.setReviewLose(false);
                    reviewResultType = "ILLEGAL";
                    tips.setVisibility(View.GONE);
                } else {
                    auditorReviewAdapter.setReviewLose(true);
                    tips.setVisibility(View.VISIBLE);
                    reviewResultType = "RESHOOT";
                }
                reviewRv.getAdapter().notifyDataSetChanged();
            }
        });
        reviewRv.post(new Runnable() {
            @Override
            public void run() {
                ptrClassicFrameLayout.autoRefresh();
            }
        });
    }

    private void initView() {
        reviewRv = findViewById(R.id.rv_auditor_operator_review);
        ptrClassicFrameLayout = findViewById(R.id.ptr_auditor_operator_review);
        loseLinearLayout = findViewById(R.id.ll_auditor_review_lose);
        reviewType = findViewById(R.id.rg_auditor_review_type);
        reviewLoseType = findViewById(R.id.rg_auditor_review_lose_type);
        LinearLayout buttonLinearLayout = findViewById(
                R.id.ll_auditor_review_button);
        auditorReviewAdapter = new AuditorReviewAdapter(mContext, auditorSealRecordsBeanList);
        manager = new GridLayoutManager(mContext, LinearLayoutManager.VERTICAL);
        reviewOk = findViewById(R.id.tv_auditor_review_ok);
        reViewCancel = findViewById(R.id.tv_auditor_review_cancel);
        tips = findViewById(R.id.tv_auditor_review_tips);
        reason = findViewById(R.id.et_auditor_review_reason);
        invalid = findViewById(R.id.rb_auditor_review_invalid);
        success = findViewById(R.id.rb_auditor_review_success);
        rePic = findViewById(R.id.rb_auditor_review_repic);
        limitWords = findViewById(R.id.tv_avditor_reviewe_words_limnit);
        if (getIntent().getBooleanExtra("isButton", true)) {
            buttonLinearLayout.setVisibility(View.VISIBLE);
            setTitleBarText("用印复审");
        } else {
            buttonLinearLayout.setVisibility(View.GONE);
            setTitleBarText("盖章记录");
        }
        reason.setFilters(new InputFilter[]{new InputFilter.LengthFilter(100)});
        reason.addTextChangedListener(new TextLengthWatch(100));
        reason.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                limitWords.setText(String.format(getString(R.string.number_limit_100), s.toString().length()));
                if (s.toString().length() == 100) {
                    limitWords.setTextColor(Color.RED);
                } else {
                    limitWords.setTextColor(Color.BLACK);
                }
            }
        });
    }

    private void sendRefuseRequest() {
        StringBuilder checkedIds = new StringBuilder();

        for (int pos = 0; pos < auditorSealRecordsBeanList.size(); pos++) {
            LogUtil.e(auditorSealRecordsBeanList.size());
            if (auditorSealRecordsBeanList.get(pos).isChecked()) {
                if (checkedIds.length() > 0) {
                    checkedIds.append(",");
                }
                checkedIds.append(auditorSealRecordsBeanList.get(pos).getSealRecordId());
            }
        }
        if (rePic.isChecked() && auditorReviewAdapter.getCount() == 0 && TextUtils.equals(status,
                "7")) {
            ShowToast.shortTime("从用印记录中至少选择一张需要补拍的图片");
            return;
        }
        if (!success.isChecked()) {
            if (TextUtils.isEmpty(reason.getText().toString())) {
                ShowToast.shortTime("请输入审核失败原因");
                return;
            }
        }
        mProcessDialog.setTitle("复审结果提交中").showNormal();
        Map<String, String> params = new HashMap<>(10);
        params.put("sealApplyId", id);
        params.put("sealRecordIds", checkedIds.toString());
        params.put("count", auditorReviewAdapter.getCount() + "");
        // 复审类型：6 成功（复审成功 ），7，失败（复审失败）
        params.put("status", status);
        // 复审结果类型：ILLEGAL 非法，RESHOOT 补拍
        params.put("reviewResultType", reviewResultType);
        params.put("reviewFailReason", reason.getText().toString());
        postJsonEnqueue(UrlConstants.REVIEW_CHECK, params, new OkHttpUtil.NetCallBack() {
            @Override
            public void onSucceed(String json) {
                mProcessDialog.dismiss();
                ShowToast.shortTime("复审成功");
                finish();
            }

            @Override
            public void onFailed(String reason) {
                mProcessDialog.dismiss();
                ShowToast.shortTime(reason);
            }
        });
    }

    private void sendListRequest(final boolean isRefresh) {
        if (isRefresh) {
            pageNo = 0;
        }
        getEnqueue(UrlConstants.SEAL_RECOREDS + id + "?page=" + pageNo, new OkHttpUtil.NetCallBack() {
            @Override
            public void onSucceed(String json) {
                if (isRefresh) {
                    auditorSealRecordsBeanList.clear();
                    reviewRv.setLoadDataListener(new AutoRecyclerView.LoadDataListener() {
                        @Override
                        public void onLoadMore() {
                            sendListRequest(false);
                        }
                    });
                }
                ptrClassicFrameLayout.refreshComplete();
                List<AuditorSealRecordsBean> auditorSealRecordsBeanTemp;
                JSONArray data;
                try {
                    data = new JSONObject(json).getJSONArray("rows");
                    auditorSealRecordsBeanTemp = new Gson().fromJson(data.toString(), new TypeToken<ArrayList<AuditorSealRecordsBean>>() {
                    }.getType());
                    auditorSealRecordsBeanList.addAll(auditorSealRecordsBeanTemp);
                    reviewRv.getAdapter().notifyDataSetChanged();
                    pageNo++;
                    if (auditorSealRecordsBeanTemp.size() < 20) {
                        reviewRv.loadMoreComplete(true);
                    } else {
                        reviewRv.loadMoreComplete(false);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailed(String reason) {
                ShowToast.shortTime(reason);
                ptrClassicFrameLayout.refreshComplete();
                reviewRv.loadMoreComplete(false);
            }
        });
    }
}
